package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.dto.LostItemDTO;
import com.csxy.six.entity.LostItem;
import com.csxy.six.mapper.LostItemMapper;
import com.csxy.six.service.LostItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class LostItemServiceImpl extends ServiceImpl<LostItemMapper, LostItem> implements LostItemService {

    @Override
    @Transactional
    public LostItem addLostItem(LostItemDTO lostItemDTO) {
        LostItem lostItem = new LostItem();
        BeanUtils.copyProperties(lostItemDTO, lostItem);
        lostItem.setIsFound(false);
        this.save(lostItem);
        return lostItem;
    }

    @Override
    public List<LostItem> getAllLostItems() {
        return this.list(new QueryWrapper<LostItem>().orderByDesc("created_at"));
    }

    @Override
    public LostItem getLostItemById(Integer lostId) {
        return this.getById(lostId);
    }

    @Override
    @Transactional
    public LostItem updateLostItem(Integer lostId, LostItemDTO lostItemDTO) {
        LostItem existingItem = this.getById(lostId);
        if (existingItem == null) {
            throw new RuntimeException("未找到ID为" + lostId + "的失物记录");
        }
        BeanUtils.copyProperties(lostItemDTO, existingItem, "lostId", "isFound", "createdAt");
        this.updateById(existingItem);
        return existingItem;
    }

    @Override
    @Transactional
    public void deleteLostItem(Integer lostId) {
        this.removeById(lostId);
    }

    @Override
    public List<LostItem> getLostItemsByPublisher(Long publisherId) {
        return this.list(new QueryWrapper<LostItem>()
                .eq("publisher_id", publisherId)
                .orderByDesc("created_at"));
    }

    @Override
    @Transactional
    public LostItem markAsFound(Integer lostId) {
        LostItem lostItem = this.getById(lostId);
        if (lostItem == null) {
            throw new RuntimeException("未找到ID为" + lostId + "的失物记录");
        }
        lostItem.setIsFound(true);
        this.updateById(lostItem);
        return lostItem;
    }
}